function [ Data ] = plotVIICorrelation( Data, Config, printPath )

%PLOTVIICORRELATION Plot Vectrino correlation data as histograms and mean profiles, returning mean 
% profiles in an updated Data structure.
%
%   Data = plotVIICorrelation( Data, Config, printPath) plots histograms and mean profiles of
%	correlation data for each beam with colorcoded range cells. Bounds corresponding to +/- one
%	standard deviation are shown on the mean profiles.
%
%	Inputs are the Data and Config structures generated during Matlab data export by the
%	Vectrino II acquistion software (also called MIDAS). An optional third argument
%	specifies a relative or absolute path for printing plots as PNGs.
%
%   See also plotVIISNR, plotVIIAmp, plotVIIVelocity.

%Copyright (c) <2012>, <Peter J. Rusello, pjrusello@gmail.com>
%All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are met:
%    * Redistributions of source code must retain the above copyright
%      notice, this list of conditions and the following disclaimer.
%    * Redistributions in binary form must reproduce the above copyright
%      notice, this list of conditions and the following disclaimer in the
%      documentation and/or other materials provided with the distribution.
%    * Neither the name of the <organization> nor the
%      names of its contributors may be used to endorse or promote products
%      derived from this software without specific prior written permission.
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
%ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
%DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
%DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
%(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
%ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

if nargin == 2
	printPath = '';
end

numberOfSamples = length( Data.Profiles_HostTime );

if isfield( Config, 'nCells' )
	nCells = Config.nCells;
elseif isfield( Config, 'Original_nCells' )
	nCells = Config.Original_nCells;
end

histogramBins = [ 0:100 ];
histogramCounts = NaN * zeros( length( Data.Profiles_Range ), length( histogramBins ), 4 );

for beam = 1:4
	Data.( [ 'Profiles_CorBeam' num2str( beam ) 'mean' ] ) = zeros( nCells, 3 );
    for cell = 1:nCells
        Data.( [ 'Profiles_CorBeam' num2str( beam ) 'mean' ] )( cell, 1 ) = mean( Data.( [ 'Profiles_CorBeam' num2str( beam ) ] )( :, cell ) );
        
        histogramCounts( cell, :, beam ) = hist( Data.( [ 'Profiles_CorBeam' num2str( beam ) ] )( :, cell ), histogramBins );
    end
end


figure
cellColors = colormap( jet( nCells ) );

for beam = 1:4
    subplot( 1, 4, beam )
    for cell = 1:nCells
        plot( Data.( [ 'Profiles_CorBeam' num2str( beam ) 'mean' ] )( cell, 1 ), Data.Profiles_Range( cell ), '.', 'color', cellColors( cell, : ), 'markersize', 10 )
        hold on
    end
    plot( Data.( [ 'Profiles_CorBeam' num2str( beam ) 'mean' ] )( :, 1 ) - std( Data.( [ 'Profiles_CorBeam' num2str( beam ) ] ) )', Data.Profiles_Range, 'k--' )
    plot( Data.( [ 'Profiles_CorBeam' num2str( beam ) 'mean' ] )( :, 1 ) + std( Data.( [ 'Profiles_CorBeam' num2str( beam ) ] ) )', Data.Profiles_Range, 'k--' )
    grid on
    set( gca, 'ydir', 'reverse', 'ylim', [ Data.Profiles_Range( 1 ) Data.Profiles_Range( end ) ] )
    set( gca, 'xlim', [ 50 100 ] )
    xlabel( [ 'B_' num2str( beam ) ] )
    if beam == 1
        ylabel( 'Cell range (m)' )
    end
end

if ~isempty( printPath )
	print( '-dpng', '-r300', [ printPath 'meanCorProfile.png' ] )
end


minBin = zeros( 4, 1 );
maxBin = zeros( 4, 1 );

figure
for beam = 1:4
    subplot( 4, 1, beam )
    for cell = 1:length( Data.Profiles_Range )
        nonzeroBins = histogramCounts( cell, :, beam ) > 0;
        plot( histogramBins( nonzeroBins ), histogramCounts( cell, nonzeroBins, beam ) / numberOfSamples, 'color', cellColors( cell, : ) )
        hold on
        if cell == 1
            minBin( beam ) = min( histogramBins( nonzeroBins ) );
            maxBin( beam ) = max( histogramBins( nonzeroBins ) );
        end
        if min( histogramBins( nonzeroBins ) ) < minBin( beam )
            minBin( beam ) = min( histogramBins( nonzeroBins ) );
        end
        if max( histogramBins( nonzeroBins ) ) > maxBin( beam )
            maxBin( beam ) = max( histogramBins( nonzeroBins ) );
        end
    end
    grid on
    set( gca, 'xlim', [ 50 100 ] )    
end
xlabel( 'Cor (dB)' )

if ~isempty( printPath )
	print( '-dpng', '-r300', [ printPath 'CorHistograms.png' ] )
end
